package com.kzd.gtgame.main.game

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.tabs.TabLayout
import com.kzd.gtgame.R
import com.kzd.gtgame.custom.setTransitionStatusE
import com.kzd.gtgame.entity.ClassifyTab
import com.kzd.gtgame.entity.GameBean
import com.kzd.gtgame.jetpack.vm.GameViewModel
import com.kzd.gtgame.main.game.adapter.Game1Adapter
import com.kzd.gtgame.main.toGameDetailsActivity
import com.module.lemlin.http.Status
import com.module.lemlin.image.loadImage
import com.module.lemlin.owner.OwnerViewModeFragment
import kotlinx.android.synthetic.main.fragment_game_ranking.*
import kotlinx.android.synthetic.main.include_app_refresh.*

class GameRankingFragment : OwnerViewModeFragment<GameViewModel>() {

    companion object {
        private const val KEY_RANKING_TYPE = "KEY_RANKING_TYPE"
        fun newInstance(type: Int): GameRankingFragment {
            val bundle: Bundle = Bundle().apply {
                putInt(KEY_RANKING_TYPE, type)
            }
            return GameRankingFragment().apply {
                arguments = bundle
            }
        }
    }

    private val mType: Int
        get() = arguments?.getInt(KEY_RANKING_TYPE) ?: 0

    private val mGame1Adapter: Game1Adapter<GameBean> by lazy {
        val type = when (mType) {
            1 -> Game1Adapter.Type.GAME_LIST_RANKING_1
            2 -> Game1Adapter.Type.GAME_LIST_RANKING_2
            else -> Game1Adapter.Type.GAME_LIST_RANKING_0
        }
        Game1Adapter(type)
    }

    override fun viewModel(): GameViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.fragment_game_ranking

    override fun initView() {

        rvAppRefreshBody.apply {
            layoutManager = LinearLayoutManager(requireContext())
        }.adapter = mGame1Adapter

        tabGameRankingKind.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                viewModel.selectedClassifyIdLiveData.postValue(
                    GameViewModel.GameUpdate((tab?.tag ?: "0").toString())
                )
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) = Unit

            override fun onTabReselected(tab: TabLayout.Tab?) = Unit
        })

        mSmartRefreshLayout.setOnRefreshListener {
            val classify = viewModel.gameClassifyLiveData.value?.data?.data

            if (classify.isNullOrEmpty()) {
                viewModel.gameClassify()
                return@setOnRefreshListener
            }
            val update = viewModel.selectedClassifyIdLiveData.value
            if (update == null) {
                mSmartRefreshLayout.finishRefresh()
            } else {
                viewModel.selectedClassifyIdLiveData.postValue(
                    GameViewModel.GameUpdate(update.type)
                )
            }
        }
        mSmartRefreshLayout.setOnLoadMoreListener {
            val update = viewModel.selectedClassifyIdLiveData.value
            if (update == null) {
                mSmartRefreshLayout.finishLoadMore()
            } else {
                viewModel.selectedClassifyIdLiveData.postValue(
                    GameViewModel.GameUpdate(update.type, isLoadMore = true)
                )
            }
        }
    }

    override fun initData() {
        viewModel.gameClassify()
    }

    override fun initViewMode() {

        viewModel.gameClassifyLiveData.observe(viewLifecycleOwner, { response ->
            setTransitionStatusE(response, mGame1Adapter, mSmartRefreshLayout)
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
            if (data.isNullOrEmpty())
                return@observe
            fillDataTab(data)
        })

        viewModel.gameRankingLiveData.observe(viewLifecycleOwner, { response ->
            setTransitionStatusE(response,mGame1Adapter,mSmartRefreshLayout)
            if (response.status != Status.SUCCESS)
                return@observe
            val isLoadMore = response.data?.isLoadMore
                ?: return@observe
            val data = response.data?.data
                ?: return@observe
            if (isLoadMore) {
                mGame1Adapter.addData(data)
                return@observe
            }
            if (mType == 0 && data.size >= 3) {
                mGame1Adapter.type = Game1Adapter.Type.GAME_LIST_RANKING_0
                val games = data.take(3)
                mGame1Adapter.setHeaderView(
                    createViewRankingTitle(games[0], games[1], games[2])
                )
                data.removeAll(games)
            } else if (mType == 0 && data.size < 3) {
                mGame1Adapter.removeAllHeaderView()
                mGame1Adapter.type = Game1Adapter.Type.GAME_LIST_RANKING_1
            }
            mGame1Adapter.setNewInstance(data)
        })

        viewModel.selectedClassifyIdLiveData.observe(viewLifecycleOwner, { update ->
            viewModel.gameRanking(mType.toString(), update.type, update.isLoadMore)
        })
    }

    private fun fillDataTab(classifyTab: MutableList<ClassifyTab>) = tabGameRankingKind.apply {
        for (item in classifyTab) addTab(newTab().apply {
            val view: View = LayoutInflater.from(requireContext())
                .inflate(R.layout.item_game_ranking_label, null)
            view.findViewById<TextView>(R.id.tvGameRankingLabelName)
                .text = item.name
            customView = view
            tag = item.id
        })
        visibility = View.VISIBLE
    }

    private fun createViewRankingTitle(
        gameList1: GameBean, gameList2: GameBean, gameList3: GameBean
    ): View {
        val view = LayoutInflater.from(requireContext())
            .inflate(R.layout.include_ranking_title, null)
        view.findViewById<ImageView>(R.id.ivGameRankingNo1Icon)
            .loadImage(
                src = gameList1.icon ?: R.mipmap.ic_80008,
                R.mipmap.ic_80008,
                R.mipmap.ic_80008
            )
        view.findViewById<ImageView>(R.id.ivGameRankingNo2Icon)
            .loadImage(
                src = gameList2.icon ?: R.mipmap.ic_80008,
                R.mipmap.ic_80008,
                R.mipmap.ic_80008
            )
        view.findViewById<ImageView>(R.id.ivGameRankingNo3Icon)
            .loadImage(
                src = gameList3.icon ?: R.mipmap.ic_80008,
                R.mipmap.ic_80008,
                R.mipmap.ic_80008
            )
        view.findViewById<TextView>(R.id.tvGameRankingNo1Name)
            .text = gameList1.name
        view.findViewById<TextView>(R.id.tvGameRankingNo2Name)
            .text = gameList2.name
        view.findViewById<TextView>(R.id.tvGameRankingNo3Name)
            .text = gameList3.name
        view.findViewById<TextView>(R.id.tvGameRankingNo1Type)
            .text = gameList1.type
        view.findViewById<TextView>(R.id.tvGameRankingNo2Type)
            .text = gameList2.type
        view.findViewById<TextView>(R.id.tvGameRankingNo3Type)
            .text = gameList3.type
        view.findViewById<TextView>(R.id.tvGameRankingNo1Down)
            .setOnClickListener {
                toGameDetailsActivity(gid = gameList1.id ?: return@setOnClickListener)
            }
        view.findViewById<TextView>(R.id.tvGameRankingNo2Down)
            .setOnClickListener {
                toGameDetailsActivity(gid = gameList2.id ?: return@setOnClickListener)
            }
        view.findViewById<TextView>(R.id.tvGameRankingNo3Down)
            .setOnClickListener {
                toGameDetailsActivity(gid = gameList3.id ?: return@setOnClickListener)
            }
        return view
    }


}